package com.lenovo.nova.util.network;

import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import com.lenovo.nova.util.debug.MyOldLog;
import com.lenovo.nova.util.debug.mylog;
import com.lenovo.nova.util.debug.slog;
import com.lenovo.nova.util.io.FileUtils;
import com.lenovo.nova.util.parse.PreferencesUtil;
import org.apache.http.HttpResponse;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class NetworkTask {

    private static final String TAG = NetworkTask.class.getSimpleName();
    private ApacheNetworkManager netManager = null;
    /**
     * 这个是经过优化的连网请求
     */
    private NetworkManagerApache mNetworkManagerIntern;

    private Context mContext;
    private DownloadBroadCast mDownloadBroadCast;

    public NetworkTask(Context context) {
        netManager = new ApacheNetworkManager(context);
        mNetworkManagerIntern = new NetworkManagerApache();
        mContext = context;
    }


    public void cancelDownload() {

    }

    public Bitmap getBitmap(String url) {
        HttpResponse entity = mNetworkManagerIntern.getResponse(false, url, null, null);
        InputStream in = null;
        try {

            if (entity != null) {
                in = entity.getEntity().getContent();
                return BitmapFactory.decodeStream(in);
            } else {
                mylog.e(TAG, "url " + url);
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void registerDownloadBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        filter.addAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
        mDownloadBroadCast = new DownloadBroadCast();
        mContext.registerReceiver(mDownloadBroadCast, filter);
    }

    public void unRegisterDownloadBroadcast() {
        mContext.unregisterReceiver(mDownloadBroadCast);
    }


    /**
     * @param url
     * @param destFile 下载的文件存放的位置
     * @param callback
     */
    public long executeDownload(String url, File destFile,
                                DownloadNotify callback,
                                DownloadManager.Request request) {
//		if (mDownloadTask == null) {
//			mDownloadTask = new DownloadInternalTask();
//		}
//		mDownloadTask.execute(url, destFile, callback, request);

        DownloadManager downloadManager =
                (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);

        long reference = PreferencesUtil.getCurrentInstance(mContext).getLong(url, 0);
        if(reference != 0){
            mylog.i(TAG," id " + reference + " already download url : " + url);

        }else{
            //初始化参数
            if (request == null) {
                request = new DownloadManager.Request(Uri.parse(url));
//				request.setTitle("downloading.....");
//				// 设置下载中通知栏提示的介绍
//
//				request.setDescription("download content");

                // if(destFile != null){
                // request.setDestinationUri(uri)
                // }
            }

            reference = downloadManager.enqueue(request);
            mylog.i(TAG,"download id is " + reference);
            PreferencesUtil.getCurrentInstance(mContext).save(url, reference);
        }

        DownloadNotifyHandler handler = new DownloadNotifyHandler();
        handler.setCallback(callback);
        handler.setDownloadManager(downloadManager);
        handler.setQueryId(reference);
        handler.setDestFile(destFile);

        Message.obtain(handler, DownloadNotifyHandler.MSG_UPDATE_PROGRESS).sendToTarget();
        return reference;
    }


    public void removeDownload(long downloadId){
        DownloadManager downloadManager =
                (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadManager.remove(downloadId);
    }


//    public void waitForFinishDownload() {
//        synchronized (this) {
//            while (!mDownloadTask.finishDownload) {
//                try {
//                    mDownloadTask.wait(0);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }



    public static interface DownloadNotify {
        void onProgress(int progress);

        void onFinishDownload(File srcFile, File destFile);

        void onError(int code);
    }

    class DownloadBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mylog.i(TAG, "onReceive " + intent.getAction());
            long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            mylog.i(TAG, "download id " + downId);
        }
    }

    private File executeDownloadFinish(File destinationFile, Cursor cursor, DownloadNotify callback) {
        int fileNameIdx = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
        int fileUriIdx = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
        String fileName = cursor.getString(fileNameIdx);
        String fileUri = cursor.getString(fileUriIdx);

        mylog.i(TAG,"fileName " + fileName + " fileUri " + fileUri);

        if (callback != null) {
            File srcFile = new File(fileName);
            if (destinationFile != null) {
                destinationFile = new File(destinationFile, fileName.substring(fileName.lastIndexOf("/")));
                FileUtils.copyFile(srcFile, destinationFile);
            }
            callback.onFinishDownload(srcFile, destinationFile);
        }

        return destinationFile;
    }


    class DownloadNotifyHandler extends Handler {

        public static final int MSG_UPDATE_PROGRESS = 0;
        private DownloadManager downloadManager;
        private long queryId;
        private DownloadNotify callback;
        private boolean finishDownload;
        private File destFile;

        public void setDownloadManager(DownloadManager downloadManager) {
            this.downloadManager = downloadManager;
        }

        public void setQueryId(long queryId) {
            this.queryId = queryId;
        }

        public void setCallback(DownloadNotify callback) {
            this.callback = callback;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_PROGRESS: {
                    Query query = new Query().setFilterById(queryId);
                    Cursor cursor = downloadManager.query(query);
                    if (cursor != null) {
                        boolean canMoveToFirst = cursor.moveToFirst();
                        mylog.i(TAG, "canMoveToFist " + canMoveToFirst);
                        if (canMoveToFirst) {
                            long totalSize = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                            long downSize = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));

                            int percent = 0;
                            if (totalSize > 0) {
                                percent = (int) (downSize * 100 / totalSize);

                                mylog.i(TAG, "download totalSize is " + totalSize + " downsize is " + downSize + " percent " + percent);
                                if (percent == 100) {
                                    destFile = executeDownloadFinish(destFile, cursor, callback);
                                    synchronized (this) {
                                        if (!finishDownload) {
                                            finishDownload = true;
                                            this.notifyAll();
                                        }
                                    }
                                }
                            }
                            callback.onProgress(percent);

                        } else {
                            finishDownload = true;
                            if(callback != null){
                                callback.onError(0);
                            }
                            MyOldLog.e("cursor.moveToFirst() fail");
                            int columnCount = cursor.getColumnCount();
                            MyOldLog.e("columnCount" + columnCount);
                            String columnNames[] = cursor.getColumnNames();
                            for (String string : columnNames) {
                                MyOldLog.e("name " + string);
                            }
                        }

                    }
                    if (!finishDownload) {
                        sendEmptyMessageDelayed(MSG_UPDATE_PROGRESS, 100);
                    } else {
                        removeMessages(MSG_UPDATE_PROGRESS);
                    }
                    break;
                }
            }
        }

        public void setDestFile(File destFile) {
            this.destFile = destFile;
        }
    }


}
